<template>
  <div class="order-submit">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="container">
        <div class="content-wrapper">
          <!-- 收货地址选择 -->
          <div class="address-section">
            <h3 class="section-title">收货地址</h3>
            <div class="address-list">
              <div
                v-for="address in addresses"
                :key="address.id"
                class="address-card"
                :class="{ active: selectedAddress === address.id }"
                @click="selectAddress(address.id)"
              >
                <div class="address-info">
                  <div class="receiver-info">
                    <span class="receiver-name">{{ address.receiver }}</span>
                    <span class="receiver-phone">{{ address.phone }}</span>
                  </div>
                  <div class="address-detail">
                    {{ address.province }} {{ address.city }} {{ address.district }} {{ address.street }}
                  </div>
                </div>
              </div>
              <div class="add-address-card" @click="addNewAddress">
                <el-icon class="add-icon"><Plus /></el-icon>
                <span>添加新地址</span>
              </div>
            </div>
          </div>

          <!-- 商品信息 -->
          <div class="product-section">
            <h3 class="section-title">商品</h3>
            <div class="product-list">
              <div
                v-for="item in orderItems"
                :key="item.id"
                class="product-item"
              >
                <div class="product-image">
                  <img :src="item.image" :alt="item.name" />
                </div>
                <div class="product-details">
                  <h4 class="product-name">{{ item.name }}</h4>
                  <div class="product-specs">
                    <span>尺码: {{ item.sizeName }}</span>
                    <span style="margin-left: 20px;">积分: {{ item.integral }}</span>
                  </div>
                </div>
                <div class="product-price">
                  <span class="price">{{ item.price }}元</span>
                  <span class="quantity">x {{ item.quantity }}</span>
                </div>
                <div class="product-total">
                  <span class="total">{{ item.price * item.quantity }}元</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 配送方式 -->
          <div class="delivery-section">
            <h3 class="section-title">配送方式</h3>
            <div class="delivery-options">
              <div
                v-for="option in deliveryOptions"
                :key="option.id"
                class="delivery-option"
                :class="{ active: selectedDelivery === option.id }"
                @click="selectDelivery(option.id)"
              >
                <div class="option-info">
                  <span class="option-name">{{ option.name }}</span>
                  <span class="option-desc">{{ option.description }}</span>
                </div>
                <div class="option-fee">
                  <span v-if="option.fee === 0">包邮</span>
                  <span v-else>¥{{ option.fee }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 费用详情 -->
          <div class="cost-section">
            <h3 class="section-title">费用</h3>
            <div class="cost-details">
              <div class="cost-item">
                <span class="cost-label">商品件数:</span>
                <span class="cost-value">{{ totalItems }}件</span>
              </div>
              <div class="cost-item">
                <span class="cost-label">商品总价:</span>
                <span class="cost-value">{{ totalPrice }}元</span>
              </div>
              <div class="cost-item">
                <span class="cost-label">可得积分:</span>
                <span class="cost-value points">{{ totalPoints }}分</span>
              </div>
              <div class="cost-item total">
                <span class="cost-label">应付总额:</span>
                <span class="cost-value final-price">{{ finalPrice }}元</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部提交按钮 -->
        <div class="submit-section">
          <div class="submit-wrapper">
            <el-button
              type="text"
              class="back-btn"
              @click="goBack"
            >
              返回
            </el-button>
            <el-button
              type="warning"
              size="large"
              class="submit-btn"
              @click="submitOrder()"
            >
              提交订单
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部服务保障 -->
    <div class="service-section">
      <div class="container">
        <div class="service-items">
          <div class="service-item">
            <el-icon class="service-icon"><CircleCheck /></el-icon>
            <span>正品保障</span>
          </div>
          <div class="service-item">
            <el-icon class="service-icon"><Clock /></el-icon>
            <span>7天无理由退货</span>
          </div>
          <div class="service-item">
            <el-icon class="service-icon"><Van /></el-icon>
            <span>15天免费换货</span>
          </div>
          <div class="service-item">
            <el-icon class="service-icon"><Coin /></el-icon>
            <span>满69元包邮</span>
          </div>
          <div class="service-item">
            <el-icon class="service-icon"><Lightning /></el-icon>
            <span>闪电发货</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import {
  Plus,
  CircleCheck,
  Clock,
  Van,
  Coin,
  Lightning
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { selectAddressMessage } from '@/api/address'
import { submitOrderMessage, submitOrderShoesMessage } from '@/api/order'
import { ElMessage } from 'element-plus'
import { deleteCartByUserId } from '@/api/cart'
import { selectCartInfo } from '@/api/user'

//import { getOrderItems, submitOrder } from '@/api/order'

const userStore = useUserStore() // 初始化用户store
const route = useRoute()
const router = useRouter()
const isNotCart = ref(false)
onMounted(() => {
  console.log(route.query)
  isNotCart.value = route.query.isNotCart
  //如果是直接支付,则直接获取订单商品数据
  if (isNotCart.value) {
    orderItems.value.push(route.query)
    console.log(orderItems.value)
  }
  //如果是从购物车列表跳转过来,则需要根据用户id获取订单商品数据
  else{
    selectCartInfo(userStore.user.uid).then(res=>{
      if(res.status === 200){
        orderItems.value = res.data
        console.log(orderItems.value)
      }
    })
  }
  console.log(orderItems.value)
  //获取用户收货地址
  selectAddressMessage(userStore.user.uid).then((res)=>{
    addresses.value = res.data
    console.log(addresses.value)
  })
})

const selectedAddress = ref(0)
const selectedDelivery = ref(1)

// 收货地址数据
const addresses = ref([])

// 订单商品数据
const orderItems = ref([])

// 配送方式选项
const deliveryOptions = ref([
  {
    id: 1,
    name: '包邮',
    description: '免费配送',
    fee: 0
  }
])

// 计算属性
const totalItems = computed(() => {
  return orderItems.value.reduce((total, item) => total + parseInt(item.quantity), 0)
})
const totalPrice = computed(() => {
  return orderItems.value.reduce((total, item) => total + (parseInt(item.price) * parseInt(item.quantity)), 0)
})
const totalPoints = computed(() => {
  return orderItems.value.reduce((total, item) => total + (parseInt(item.integral) * parseInt(item.quantity)), 0)
})

const finalPrice = computed(() => {
  const deliveryFee = deliveryOptions.value.find(option => option.id === selectedDelivery.value)?.fee || 0
  return totalPrice.value + deliveryFee
})

// 方法
const selectAddress = (addressId) => {
  selectedAddress.value = addressId
}
const selectDelivery = (deliveryId) => {
  selectedDelivery.value = deliveryId
}
//添加新地址
const addNewAddress = () => {
  router.push({ name: 'addressManagement' })
}

const goBack = () => {
  router.back()
}

const orderForm = ref({
  uid: userStore.user.uid,//用户id
  addressId: 0,//地址id
  principal: 0,//订单金额
  points: 0,//订单积分
})
const orderShoesForm = ref({
  uid: 0,//用户id
  orderId: 0,//订单id
  shoesId: 0,//鞋子id
  quantity: 0,//购买数量
  price: 0,//单价
  integral: 0,//积分
  sizeID: 0,//尺码id
})
const submitOrder = () => {
  console.log('提交订单')
  orderForm.value.addressId=selectedAddress.value
  orderForm.value. principal=totalPrice.value
  orderForm.value.points=totalPoints.value

  console.log(orderForm.value)
  if(!orderForm.value.addressId){
    ElMessage.warning('请选择地址')
    return
  }
  submitOrderMessage(orderForm.value).then(res => {
    if (res.status === 200) {
      ElMessage.success('订单提交成功')
      //提交订单商品数据
      orderShoesForm.value.orderId=res.data.orderId
      if(isNotCart.value){
        orderShoesForm.value.shoesId=orderItems.value[0].id
        orderShoesForm.value.quantity=orderItems.value[0].quantity
        orderShoesForm.value.price=orderItems.value[0].price
        orderShoesForm.value.integral=orderItems.value[0].integral
        orderShoesForm.value.sizeID=orderItems.value[0].sizeID
        submitOrderShoesMessage(orderShoesForm.value).then(res => {
        })
      }else{
        orderItems.value.forEach(item => {
        orderShoesForm.value.uid=userStore.user.uid
        orderShoesForm.value.shoesId=item.id
        orderShoesForm.value.quantity=item.quantity
        orderShoesForm.value.price=item.price
        orderShoesForm.value.integral=item.integral
        orderShoesForm.value.sizeID=item.sizeID
        submitOrderShoesMessage(orderShoesForm.value).then(res => {
        })
      })
      deleteCartByUserId(userStore.user.uid).then(res => {
          if (res.status === 200) {
            ElMessage.success('购物车清空成功')
          }else{
            ElMessage.error('购物车清空失败')
          }
      })
      }
      router.push({ name: 'orderSuccess' })
    }
  })
}
</script>

<style scoped>
.order-submit {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

/* Header */
.header {
  background: linear-gradient(135deg, #ff8c00 0%, #ffa500 100%);
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.header-content {
  display: flex;
  align-items: center;
  padding: 15px 0;
  gap: 30px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.brand-name {
  font-size: 20px;
  font-weight: bold;
  color: white;
}

.page-title h2 {
  color: white;
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

/* Main Content */
.main-content {
  padding: 30px 0;
}

.content-wrapper {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px 0;
  padding: 20px 30px 0 30px;
}

/* Address Section */
.address-section {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 20px;
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
  padding: 0 30px;
}

.address-card {
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.address-card.active {
  border-color: #ff8c00;
  background-color: #fff4e6;
}

.address-card:hover {
  border-color: #ff8c00;
}

.receiver-info {
  display: flex;
  gap: 15px;
  margin-bottom: 8px;
}

.receiver-name {
  font-weight: 600;
  color: #333;
}

.receiver-phone {
  color: #666;
}

.address-detail {
  color: #666;
  font-size: 14px;
  line-height: 1.4;
  margin-bottom: 10px;
}

.edit-btn {
  color: #ff8c00 !important;
  padding: 0;
}

.add-address-card {
  border: 2px dashed #d0d0d0;
  border-radius: 8px;
  padding: 30px 15px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  color: #999;
}

.add-address-card:hover {
  border-color: #ff8c00;
  color: #ff8c00;
}

.add-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

/* Product Section */
.product-section {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 20px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 15px 30px;
  border-bottom: 1px solid #f5f5f5;
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 20px;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
  background-color: #f0f0f0;
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0 0 8px 0;
}

.product-specs {
  font-size: 14px;
  color: #666;
}

.product-price {
  text-align: center;
  margin: 0 30px;
}

.price {
  display: block;
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
}

.quantity {
  font-size: 14px;
  color: #666;
}

.product-total {
  text-align: right;
  min-width: 100px;
}

.total {
  font-size: 18px;
  font-weight: 600;
  color: #e74c3c;
}

/* Delivery Section */
.delivery-section {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 20px;
}

.delivery-options {
  padding: 0 30px;
}

.delivery-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.delivery-option:last-child {
  margin-bottom: 0;
}

.delivery-option.active {
  border-color: #ff8c00;
  background-color: #fff4e6;
}

.delivery-option:hover {
  border-color: #ff8c00;
}

.option-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  display: block;
}

.option-desc {
  font-size: 14px;
  color: #666;
}

.option-fee {
  font-size: 16px;
  font-weight: 600;
  color: #e74c3c;
}

/* Cost Section */
.cost-section {
  padding-bottom: 20px;
}

.cost-details {
  padding: 0 30px;
}

.cost-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  font-size: 14px;
}

.cost-item.total {
  border-top: 1px solid #f0f0f0;
  margin-top: 10px;
  padding-top: 15px;
  font-size: 16px;
}

.cost-label {
  color: #666;
}

.cost-value {
  color: #333;
}

.cost-value.points {
  color: #ff8c00;
}

.cost-value.discount {
  color: #27ae60;
}

.cost-value.final-price {
  font-size: 20px;
  font-weight: bold;
  color: #e74c3c;
}

/* Submit Section */
.submit-section {
  margin-top: 30px;
  padding: 20px 0;
}

.submit-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px 30px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.back-btn {
  color: #666 !important;
}

.submit-btn {
  padding: 12px 40px;
  font-size: 16px;
  font-weight: 600;
}

/* Service Section */
.service-section {
  background: #f8f9fa;
  padding: 30px 0;
  margin-top: 30px;
}

.service-items {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.service-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #666;
}

.service-icon {
  font-size: 24px;
  color: #ff8c00;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .address-list {
    grid-template-columns: 1fr;
  }

  .product-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
    padding: 20px 15px;
  }

  .product-price,
  .product-total {
    margin: 0;
    text-align: left;
  }

  .submit-wrapper {
    flex-direction: column;
    gap: 15px;
  }

  .submit-btn {
    width: 100%;
  }

  .service-items {
    flex-direction: column;
    gap: 20px;
  }
}
</style>